import { useState, type FormEvent } from 'react'

interface LoginFormProps {
  onSuccess?: (user: any, token: string) => void
  onSwitchToRegister?: () => void
}

interface LoginData {
  email: string
  password: string
}

interface ApiResponse {
  code: number
  message: string
  data?: {
    user?: any
    token?: string
  }
  error?: string
}

export default function LoginForm({ onSuccess, onSwitchToRegister }: LoginFormProps) {
  const [formData, setFormData] = useState<LoginData>({
    email: '',
    password: ''
  })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError('')

    try {
      const response = await fetch('http://localhost:8080/api/v1/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      })
      
      const data: ApiResponse = await response.json()
      
      if (data.code === 1 && data.data && data.data.user && data.data.token) {
        // 保存token到localStorage
        console.log("保存token到localStorage", data.data.token)
        
        localStorage.setItem('auth_token', data.data.token)
        localStorage.setItem('user', JSON.stringify(data.data.user))
        
        if (onSuccess) {
          onSuccess(data.data.user, data.data.token)
        }
      } else {
        setError(data.error || data.message || '登录失败')
      }
    } catch (err) {
      setError('网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const handleInputChange = (field: keyof LoginData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }))
  }

  return (
    <div className="card" style={{ maxWidth: '400px', margin: '0 auto' }}>
      <div className="card-header">
        <h2 className="card-title text-center">登录</h2>
        <p className="card-description text-center">欢迎回到 AI Prompt Hub</p>
      </div>
      <div className="card-content">
        <form onSubmit={handleSubmit} className="space-y-3">
          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-md">
              <p className="text-red-600 text-sm">{error}</p>
            </div>
          )}
          
          <div>
            <label htmlFor="email" className="block text-sm font-medium mb-1">
              邮箱地址
            </label>
            <input
              id="email"
              type="email"
              required
              className="input"
              placeholder="请输入邮箱地址"
              value={formData.email}
              onChange={(e) => handleInputChange('email', e.target.value)}
            />
          </div>

          <div>
            <label htmlFor="password" className="block text-sm font-medium mb-1">
              密码
            </label>
            <input
              id="password"
              type="password"
              required
              className="input"
              placeholder="请输入密码"
              value={formData.password}
              onChange={(e) => handleInputChange('password', e.target.value)}
            />
          </div>

          <button
            type="submit"
            disabled={loading}
            className={`btn btn-primary w-full ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
          >
            {loading ? '登录中...' : '登录'}
          </button>
        </form>

        <div className="mt-4 text-center">
          <p className="text-sm text-muted">
            还没有账号？{' '}
            <button
              type="button"
              onClick={onSwitchToRegister}
              className="text-primary hover:underline"
            >
              立即注册
            </button>
          </p>
        </div>
      </div>
    </div>
  )
}